package ext.tianma.bom.service;

import java.beans.PropertyVetoException;
import java.io.File;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ptc.core.meta.type.mgmt.server.impl.WTTypeDefinition;

import ext.drawing.BorrowWorkflowUtil;
import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.util.PropertiesUtil;
import wt.access.AccessControlHelper;
import wt.access.AccessPermission;
import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentItem;
import wt.content.FormatContentHolder;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.enterprise.Master;
import wt.enterprise.RevisionControlled;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.iba.definition.StringDefinition;
import wt.iba.value.DefaultAttributeContainer;
import wt.iba.value.IBAHolder;
import wt.iba.value.StringValue;
import wt.iba.value.IBAValueUtility;
import wt.iba.value.litevalue.AbstractValueView;
import wt.iba.value.litevalue.StringValueDefaultView;
import wt.iba.value.service.IBAValueHelper;
import wt.inf.container.ExchangeContainer;
import wt.inf.container.WTContainerHelper;
import wt.lifecycle.State;
import wt.method.RemoteMethodServer;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTOrganization;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartMaster;
import wt.part.WTPartReferenceLink;
import wt.part.WTPartStandardConfigSpec;
import wt.pds.StatementSpec;
import wt.query.ClassAttribute;
import wt.query.KeywordExpression;
import wt.query.OrderBy;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlException;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigHelper;
import wt.vc.views.View;
import wt.vc.views.ViewException;
import wt.vc.views.ViewHelper;

public class DrawingHelp {
	private static Locale LOCALE = Locale.CHINA;
	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";

	/**
	 * 设置返回数据
	 * 
	 * @param list
	 * @throws WTException
	 * @throws PropertyVetoException
	 */
	public static JSONArray setData(List<WTDocument> list) throws WTException, PropertyVetoException {
		ReferenceFactory rf = new ReferenceFactory();
		JSONArray array = new JSONArray();
		WTPart part = null;
		String partNum = "";
		String docUrl = "";
		String type = "";
		String version = "";
		String suffix = "";
		String primaryName = "";

		try {
			for (int i = 0; i < list.size(); i++) {
				JSONObject obj = new JSONObject();
				WTDocument doc = list.get(i);
				if (!State.RELEASED.equals(doc.getLifeCycleState())) {
					continue;
				}

				primaryName = getDocPrimaryName(doc);
				suffix = primaryName.substring(primaryName.lastIndexOf(".") + 1);

				docUrl = ShowDocHelper.getDocPath(doc);
				part = getReferencePart(doc);
				String oid = rf.getReferenceString(doc);
				String cioids = getPrimaryId(doc);
				version = getVersion(doc);
				type = typeOfDoc(doc);

				if ("工艺文件".equals(type)) {
					// 后缀忽略大小写
					if ("pdf".equalsIgnoreCase(suffix) || "xls".equalsIgnoreCase(suffix)
							|| "xlsx".equalsIgnoreCase(suffix) || "xlsm".equalsIgnoreCase(suffix)) {
						version = getIBAStringValue(doc, "cn.tianma.docVersion");
						if ("".equals(version) || version == null) {
							String docName = doc.getName();
							version = docName.substring(docName.length() - 3, docName.length());
							if (!version.contains(".")) {
								version = "";
							}
						}
					} else {
						continue;
					}

				}

				if (part == null) {
					obj.put("docOid", oid);
					obj.put("cioids", cioids);
					obj.put("partNumber", "");
					obj.put("partName", "");
					obj.put("docUrl", docUrl);
					obj.put("docNumber", doc.getNumber());
					obj.put("docName", doc.getName());
					obj.put("docVersion", version);
					array.put(obj);
				} else {

					partNum = part.getNumber();
					if ("受控PDF图纸".equals(type)) {
						version = getIBAStringValue(doc, "cn.tianma.docVersion");
						if ("".equals(version) || version == null) {
							version = "0" + partNum.charAt(partNum.length() - 1);
						}

					}

					obj.put("docOid", oid);
					obj.put("cioids", cioids);
					obj.put("partNumber", part.getNumber());
					obj.put("partName", part.getName());
					obj.put("docUrl", docUrl);
					obj.put("docNumber", doc.getNumber());
					obj.put("docName", doc.getName());
					obj.put("docVersion", version);
					array.put(obj);
				}

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("=======setData Exception:" + e);
			e.printStackTrace();
		}
		return array;

	}

	// 为part设置传回数据时候，直接带回用户输入的number
	public static JSONArray setDataa(List<WTDocument> list, String number) throws Exception {
		ReferenceFactory rf = new ReferenceFactory();
		JSONArray array = new JSONArray();
		WTPart part = getWTPartByNumber(number);
		String partNum = "";
		String docUrl = "";
		String type = "";
		String version = "";
		String suffix = "";
		String primaryName = "";

		if (list.size() == 0) {
			JSONObject obj = new JSONObject();
			obj.put("docOid", "");
			obj.put("cioids", "");
			obj.put("partNumber", part.getNumber());
			obj.put("partName", part.getName());
			obj.put("docUrl", docUrl);
			obj.put("docNumber", "");
			obj.put("docName", "");
			obj.put("docVersion", "");
			array.put(obj);
		} else {
			try {

				for (int i = 0; i < list.size(); i++) {
					JSONObject obj = new JSONObject();
					WTDocument doc = list.get(i);
					if (!State.RELEASED.equals(doc.getLifeCycleState())) {
						continue;
					}

					primaryName = getDocPrimaryName(doc);
					suffix = primaryName.substring(primaryName.lastIndexOf(".") + 1);

					docUrl = ShowDocHelper.getDocPath(doc);
					String oid = rf.getReferenceString(doc);
					String cioids = getPrimaryId(doc);
					version = getVersion(doc);
					type = typeOfDoc(doc);

					if ("工艺文件".equals(type)) {
						if ("pdf".equals(suffix) || "xls".equals(suffix) || "xlsx".equals(suffix)) {
							version = getIBAStringValue(doc, "cn.tianma.docVersion");
							if ("".equals(version) || version == null) {
								String docName = doc.getName();
								version = docName.substring(docName.length() - 3, docName.length());
								if (!version.contains(".")) {
									version = "";
								}
							}
						} else {
							continue;
						}

					}

					if (part == null) {
						obj.put("docOid", oid);
						obj.put("cioids", cioids);
						obj.put("partNumber", "");
						obj.put("partName", "");
						obj.put("docUrl", docUrl);
						obj.put("docNumber", doc.getNumber());
						obj.put("docName", doc.getName());
						obj.put("docVersion", version);
						array.put(obj);
					} else {

						partNum = part.getNumber();
						if ("受控PDF图纸".equals(type)) {
							version = "0" + partNum.charAt(partNum.length() - 1);
						}

						obj.put("docOid", oid);
						obj.put("cioids", cioids);
						obj.put("partNumber", part.getNumber());
						obj.put("partName", part.getName());
						obj.put("docUrl", docUrl);
						obj.put("docNumber", doc.getNumber());
						obj.put("docName", doc.getName());
						obj.put("docVersion", version);
						array.put(obj);
					}

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return array;

	}

	public static String getVersion(WTDocument doc) {
		String version = null;
		try {
			version = VersionControlHelper.getIterationDisplayIdentifier(doc).toString();
		} catch (VersionControlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 根据部件编号获取最新版本的部件
	 * 
	 * @param number
	 * @return
	 * @throws Exception
	 */
	public static WTPart getWTPartByNumber(String number) throws Exception {
		WTPart part = null;
		QuerySpec spec = new QuerySpec(WTPartMaster.class);
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.LIKE, number);
		spec.appendSearchCondition(sc);
		QueryResult qr = PersistenceHelper.manager.find((StatementSpec) spec);

		while (qr.hasMoreElements()) {
			WTPartMaster master = (WTPartMaster) qr.nextElement();
			// 根据master得到最新版本的零件
			part = getLatestPart(master);
			break;
		}
		if (part != null) {
		}
		return part;
	}

	/**
	 * 根据WTPartMaster获得最新版WTPart
	 * 
	 * @param partMaster
	 * @return
	 * @throws Exception
	 */
	public static WTPart getLatestPart(WTPartMaster partMaster) throws Exception {
		WTPart part = null;
		if (partMaster != null) {
			QueryResult qr = VersionControlHelper.service.allVersionsOf(partMaster);
			if (qr != null && qr.hasMoreElements()) {
				part = (WTPart) qr.nextElement();
			}
		}
		return part;
	}

	/*
	 * public static List<WTDocument> getLatestWTDocumentByNumber(String docNumber)
	 * { List<WTDocument> docList = new ArrayList<WTDocument>(); try { QuerySpec qs
	 * = new QuerySpec(WTDocument.class); SearchCondition temp = new
	 * SearchCondition(WTDocument.class, WTDocument.NUMBER, SearchCondition.EQUAL,
	 * docNumber.toUpperCase()); qs.appendSearchCondition(temp); qs.appendAnd();
	 * SearchCondition latest =
	 * VersionControlHelper.getSearchCondition(WTDocument.class, true);
	 * qs.appendSearchCondition(latest);
	 * 
	 * System.out.println("---qs getDocByNum:"+qs.toString()); QueryResult qr =
	 * PersistenceHelper.manager.find(qs); if (qr.hasMoreElements()) { WTDocument
	 * doc = (WTDocument) qr.nextElement(); docList.add(doc); } } catch (Exception
	 * e) { e.printStackTrace(); } return docList; }
	 */

	/**
	 * 获取不同文档小类下修改时间最新的图纸
	 * 
	 * @param list
	 * @return
	 * @throws WTException
	 */
	public static Map<String, WTDocument> getLatestDoc(List<WTDocument> list) throws WTException {
		Map<String, WTDocument> map = new HashMap();
		String smallDocValue = "";
		for (WTDocument doc : list) {
			smallDocValue = getIBAStringValue(doc, "SmallDocType");
			System.out.println("---文档小类值：" + smallDocValue);
			/*
			 * if(map.size()==0) { map.put(smallDocValue, doc); } else {
			 */

			// 若文档小类相同，取修改时间最新
			WTDocument value = map.get(smallDocValue);
			if (map.containsKey(smallDocValue) && (value != null && doc.getName().equals(value.getName()))) {
				WTDocument wtDocument = map.get(smallDocValue);
				//System.out.println("====wtDocument:" + wtDocument + "=====smallDocValue:" + smallDocValue);
				Timestamp timestamp1 = doc.getModifyTimestamp();
				//System.out.println("---新文档：" + doc.getNumber() + ",修改时间:" + timestamp1.getTime());
				Timestamp timestamp2 = wtDocument.getModifyTimestamp();
				//System.out.println("---现有文档：" + wtDocument.getNumber() + ",修改时间:" + timestamp2.getTime());
				//System.out.println("====before:" + timestamp2.before(timestamp1));
				if (timestamp2.before(timestamp1)) {
					// map.remove(smallDocValue);
					map.put(smallDocValue, doc);
				}
			} else {
				map.put(smallDocValue, doc);
			}
			// }
		}

		return map;

	}

	/**
	 * IQC组人员 获取最新修改时间的受控PDF文档
	 * 
	 * @param list
	 * @return
	 * @throws WTException
	 */
	public static Map<String, WTDocument> getLatestPDFDoc(List<WTDocument> list) throws WTException {
		Map<String, WTDocument> map = new HashMap();
		String dockey = "pdfdoc";
		for (WTDocument doc : list) {
			if (map.containsKey(dockey)) {
				WTDocument wtDocument = map.get(dockey);
				Timestamp timestamp1 = doc.getModifyTimestamp();
				//System.out.println("---新文档：" + doc.getNumber() + ",修改时间:" + timestamp1.getTime());
				Timestamp timestamp2 = wtDocument.getModifyTimestamp();
				//System.out.println("---现有文档：" + wtDocument.getNumber() + ",修改时间:" + timestamp2.getTime());
				//System.out.println("====before:" + timestamp2.before(timestamp1));
				if (timestamp2.before(timestamp1)) {
					map.put(dockey, doc);
				}
			} else {
				map.put(dockey, doc);
			}
			// }
		}

		return map;

	}

	/**
	 * 根据文档获取关联的部件
	 * 
	 * @param doc
	 * @return
	 * @throws WTException
	 */
	public static WTPart getReferencePart(WTDocument doc) throws WTException {
		WTPart part = null;
		try {
			if (!RemoteMethodServer.ServerFlag) {
				RemoteMethodServer.getDefault().invoke("getReferencePart", DrawingHelp.class.getName(), null,
						new Class[] { WTPart.class, WTDocument.class }, new Object[] {});
			} else {
				QueryResult qr = null;
				qr = PersistenceHelper.manager.navigate(doc, WTPartDescribeLink.DESCRIBES_ROLE,
						WTPartDescribeLink.class, false);
				while (qr.hasMoreElements()) {
					WTPartDescribeLink link = (WTPartDescribeLink) qr.nextElement();
					// WTDocument p = link.getDescribedBy();
					if (link != null) {
						part = link.getDescribes();

					}
				}
			}

		} catch (Exception e) {

		}

		return part;

	}

	/**
	 * 获取要展示的所有文档，包括参考文档和说明文档
	 * 
	 * @param part
	 * @return
	 * @throws Exception
	 */
	public static List<WTDocument> getDocList(WTPart part) throws Exception {

		List<WTDocument> allDocList = new ArrayList<WTDocument>();
		List<WTDocument> lastDocList = new ArrayList<WTDocument>();
		String curGroup = groupOfUser();

		// WTArrayList viewPartList = getAllViewParts(part);// 获取所有视图
		WTArrayList viewPartList = new WTArrayList();
		// update 查找Design的视图
		WTPart designpart = BOMHelp.getPart(part.getNumber(), "", "Design");
		if (designpart != null) {
			viewPartList.add(designpart);
		}

		System.out.println("---part viewList:" + viewPartList.size());
		for (int j = 0; j < viewPartList.size(); j++) {// 循环查找所有视图的子件判断
			// 根据part得到参考关系的文档集合
			WTPart p = (WTPart) viewPartList.getPersistable(j);
			List<WTDocument> referenceList = getReferenceDoc(p);
			//System.out.println("部件编码：" + p.getNumber() + ",---refDocList:" + referenceList.size());
			// 获取说明文档
			List<WTDocument> describeList = getDescribeDoc(p);
			//System.out.println("部件编码：" + p.getNumber() + "---desDocList:" + describeList.size());
			allDocList.addAll(referenceList);
			allDocList.addAll(describeList);
		}
		//System.out.println("根据编号去重前list.size:" + allDocList.size() + "==allDocList:" + allDocList.toString());
		List<WTDocument> newAllDocList = new ArrayList<WTDocument>(new HashSet(allDocList));// 去重

		//System.out.println("根据编号去重后list.size:" + newAllDocList.size());
		// 工厂组查询出多个工艺文件时，判断文档小类，若相同，取最修改时间最新的，若不同，取各自修改时间最新的
		if ("FACGroup".equals(curGroup)) {
			Map<String, WTDocument> map = getLatestDoc(newAllDocList);
			for (String key : map.keySet()) {
				WTDocument doc = map.get(key);
				lastDocList.add(doc);

			}
		} else if ("IQCGroup".equals(curGroup)) {
			// 取最新修改时间的受控PDF
			Map<String, WTDocument> map = getLatestPDFDoc(newAllDocList);
			for (String key : map.keySet()) {
				WTDocument doc = map.get(key);
				lastDocList.add(doc);

			}
		} else {
			lastDocList = newAllDocList;
		}

		/*
		 * for (int i = 0; i < newAllDocList.size(); i++) { doc = newAllDocList.get(i);
		 * if (!part.getNumber().startsWith("1")) { if ("工艺文件".equals(typeOfDoc(doc))) {
		 * lastDocList.add(doc); } } else { if ("受控PDF图纸".equals(typeOfDoc(doc))) {
		 * lastDocList.add(doc); } } }
		 */

		return lastDocList;
	}

	/**
	 * 根据部件获取参考文档
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static List<WTDocument> getReferenceDoc(WTPart part) throws WTException, RemoteException {
		String curGroup = groupOfUser();
		System.out.println("---ref curGroup:" + curGroup);
		String SmallDocType = "SmallDocType";
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String smallDocList = ut.getValueByKey("smallDocType.list");
		String ControlDocument = ut.getValueByKey("IQC.queryType");
		String ProcessDocuments = ut.getValueByKey("FAC.queryType");
		String smallDocs[] = smallDocList.split(";");

		long ida2a2 = PersistenceHelper.getObjectIdentifier(part).getId();
		List<WTDocument> docList = new ArrayList<WTDocument>();
		QuerySpec qs = new QuerySpec();
		int indexOfLink = qs.appendClassList(WTPartReferenceLink.class, false);
		int indexOfDocMater = qs.appendClassList(WTDocumentMaster.class, true);
		int indexOfProduct = qs.appendClassList(WTPart.class, false);
		int indexOfDoc = qs.appendClassList(WTDocument.class, false);
		int indexOfType = qs.appendClassList(WTTypeDefinition.class, false);

		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida3a5"), SearchCondition.EQUAL,
				new KeywordExpression("A2.IdA2a2")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida3b5"), SearchCondition.EQUAL,
				new KeywordExpression("A1.IdA2a2")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A1.IdA2a2"), SearchCondition.EQUAL,
				new KeywordExpression("A3.Ida3masterreference")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A2.ida2a2"), SearchCondition.EQUAL,
				new KeywordExpression("'" + ida2a2 + "'")));

		if ("FACGroup".equals(curGroup)) {
			// 文档类型 工艺文件
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.Ida2typedefinitionreference"),
					SearchCondition.EQUAL, new KeywordExpression("A4.ida2a2")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A4.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + ProcessDocuments + "'")));

			int valueIndex = qs.appendClassList(StringValue.class, false);
			int defIndex = qs.appendClassList(StringDefinition.class, false);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.ida2a2"), SearchCondition.EQUAL,
					new KeywordExpression("A5.ida3a4")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A5.ida3a6"), SearchCondition.EQUAL,
					new KeywordExpression("A6.ida2a2")));

			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A6.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + SmallDocType + "'")));
			qs.appendAnd();
			qs.appendOpenParen();// 左括号

			for (int i = 0; i < smallDocs.length; i++) {
				if (i != 0) {
					qs.appendOr();// 或者
				}
				qs.appendWhere(new SearchCondition(new KeywordExpression("A5.value2"), SearchCondition.LIKE,
						new KeywordExpression("'%" + smallDocs[i] + "%'")));
			}
			qs.appendCloseParen();// 右括号

			/*
			 * ClassAttribute value2 = new
			 * ClassAttribute(StringValue.class,StringValue.VALUE2);
			 * qs.appendGroupBy(value2, new int[]{valueIndex}, false);
			 */

		} else if ("IQCGroup".equals(curGroup)) {
			// 文档类型 受控PDF
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.Ida2typedefinitionreference"),
					SearchCondition.EQUAL, new KeywordExpression("A4.ida2a2")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A4.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + ControlDocument + "'")));
		}
		qs.appendOrderBy(new OrderBy(new KeywordExpression("A3.MODIFYSTAMPA2"), true));
		System.out.println("---getReferenceDoc sql:" + qs);

		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			Object[] obj = (Object[]) qr.nextElement();
			WTDocumentMaster master = (WTDocumentMaster) obj[0];
			WTDocument doc = (WTDocument) getLatestRevision(master);
			// 增加状态校验
			if (State.RELEASED.equals(doc.getLifeCycleState())) {
				docList.add(doc);
				if ("IQCGroup".equals(curGroup)) {
					break;
				}
			}

		}

		return docList;

	}

	/**
	 * 根据部件获取说明文档
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static List<WTDocument> getDescribeDoc(WTPart part) throws WTException, RemoteException {
		String curGroup = groupOfUser();
		System.out.println("---des curGroup:" + curGroup);
		String SmallDocType = "SmallDocType";
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String smallDocList = ut.getValueByKey("smallDocType.list");
		String ControlDocument = ut.getValueByKey("IQC.queryType");
		String ProcessDocuments = ut.getValueByKey("FAC.queryType");
		String smallDocs[] = smallDocList.split(";");

		long ida2a2 = PersistenceHelper.getObjectIdentifier(part).getId();
		System.out.println(
				"---part number:" + part.getNumber() + ",part view:" + part.getViewName() + ",part ida2a2:" + ida2a2);
		List<WTDocument> docList = new ArrayList<WTDocument>();
		QuerySpec qs = new QuerySpec();
		int indexOfLink = qs.appendClassList(WTPartDescribeLink.class, false);
		int indexOfDoc = qs.appendClassList(WTDocument.class, true);
		int indexOfProduct = qs.appendClassList(WTPart.class, false);
		int indexOfType = qs.appendClassList(WTTypeDefinition.class, false);

		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida3a5"), SearchCondition.EQUAL,
				new KeywordExpression("A2.IdA2a2")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida3b5"), SearchCondition.EQUAL,
				new KeywordExpression("A1.IdA2a2")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A2.ida2a2"), SearchCondition.EQUAL,
				new KeywordExpression("'" + ida2a2 + "'")));

		if ("FACGroup".equals(curGroup)) {
			// 文档类型 工艺文件
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.Ida2typedefinitionreference"),
					SearchCondition.EQUAL, new KeywordExpression("A3.ida2a2")));

			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + ProcessDocuments + "'")));

			int valueIndex = qs.appendClassList(StringValue.class, false);
			int defIndex = qs.appendClassList(StringDefinition.class, false);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.ida2a2"), SearchCondition.EQUAL,
					new KeywordExpression("A4.ida3a4")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A4.ida3a6"), SearchCondition.EQUAL,
					new KeywordExpression("A5.ida2a2")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A5.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + SmallDocType + "'")));
			qs.appendAnd();
			qs.appendOpenParen();// 左括号

			for (int i = 0; i < smallDocs.length; i++) {
				if (i != 0) {
					qs.appendOr();// 或者
				}
				qs.appendWhere(new SearchCondition(new KeywordExpression("A4.value2"), SearchCondition.LIKE,
						new KeywordExpression("'%" + smallDocs[i] + "%'")));
			}
			qs.appendCloseParen();// 右括号

			/*
			 * ClassAttribute value2 = new
			 * ClassAttribute(StringValue.class,StringValue.VALUE2);
			 * qs.appendGroupBy(value2, new int[]{valueIndex}, false);
			 */

		} else if ("IQCGroup".equals(curGroup)) {
			// 文档类型 受控PDF图纸
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.Ida2typedefinitionreference"),
					SearchCondition.EQUAL, new KeywordExpression("A3.ida2a2")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + ControlDocument + "'")));
		}
		qs.appendOrderBy(new OrderBy(new KeywordExpression("A1.MODIFYSTAMPA2"), true));
		System.out.println("---getDescribeDoc sql:" + qs);

		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			Object[] obj = (Object[]) qr.nextElement();
			WTDocument dd = new WTDocument();
			dd = (WTDocument) obj[0];
			WTDocumentMaster master = (WTDocumentMaster) dd.getMaster();
			WTDocument doc = (WTDocument) getLatestRevision(master);
			/*
			 * docList.add(doc); if ("IQCGroup".equals(curGroup)) { break; }
			 */

			// 增加状态校验
			if (State.RELEASED.equals(doc.getLifeCycleState())) {
				docList.add(doc);
				if ("IQCGroup".equals(curGroup)) {
					break;
				}
			}

		}

		return docList;
	}

	/**
	 * 获取文档的最新版本
	 * 
	 * @param master
	 * @return
	 */
	public static RevisionControlled getLatestRevision(Master master) {
		try {
			if (!RemoteMethodServer.ServerFlag) {
				return (RevisionControlled) RemoteMethodServer.getDefault().invoke("getLatestRevision",
						DrawingHelp.class.getName(), null, new Class[] { Master.class }, new Object[] { master });
			} else {
				boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
				RevisionControlled rc = null;
				if (master != null) {
					try {
						QueryResult qr = VersionControlHelper.service.allVersionsOf(master);
						while (qr.hasMoreElements()) {
							RevisionControlled obj = (RevisionControlled) qr.nextElement();
							if ((rc == null) || (obj.getVersionIdentifier().getSeries()
									.greaterThan(rc.getVersionIdentifier().getSeries()))) {
								rc = obj;
							}
						}
						if (rc != null)
							rc = (RevisionControlled) VersionControlHelper.getLatestIteration(rc, false);
					} catch (WTException e) {

					} finally {
						SessionServerHelper.manager.setAccessEnforced(enforce);
					}
				}
				return rc;
			}
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 根据number获取文档
	 * 
	 * @param number
	 * @return
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static List<WTDocument> getWTDocumentByNumber(String number) throws RemoteException, WTException {
		String curGroup = groupOfUser();
		String SmallDocType = "SmallDocType";
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String smallDocList = ut.getValueByKey("smallDocType.list");
		String ControlDocument = ut.getValueByKey("IQC.queryType");
		String ProcessDocuments = ut.getValueByKey("FAC.queryType");
		String smallDocs[] = smallDocList.split(";");
		List<WTDocument> docList = new ArrayList<WTDocument>();
		WTDocument doc = null;

		try {

			QuerySpec qs = new QuerySpec();
			int indexOfDocMater = qs.appendClassList(WTDocument.class, true);
			int indexOfDoc = qs.appendClassList(WTDocumentMaster.class, false);
			int indexOfType = qs.appendClassList(WTTypeDefinition.class, false);

			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.WTDocumentNumber"), SearchCondition.EQUAL,
					new KeywordExpression("'" + number + "'")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.IdA2a2"), SearchCondition.EQUAL,
					new KeywordExpression("A0.Ida3masterreference")));

			if ("FACGroup".equals(curGroup)) {
				// 文档类型 工艺文件
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A0.Ida2typedefinitionreference"),
						SearchCondition.EQUAL, new KeywordExpression("A2.ida2a2")));
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A2.name"), SearchCondition.EQUAL,
						new KeywordExpression("'" + ProcessDocuments + "'")));

				int valueIndex = qs.appendClassList(wt.iba.value.StringValue.class, false);
				int defIndex = qs.appendClassList(StringDefinition.class, false);
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida2a2"), SearchCondition.EQUAL,
						new KeywordExpression("A3.ida3a4")));
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A3.ida3a6"), SearchCondition.EQUAL,
						new KeywordExpression("A4.ida2a2")));

				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A4.name"), SearchCondition.EQUAL,
						new KeywordExpression("'" + SmallDocType + "'")));
				qs.appendAnd();
				qs.appendOpenParen();// 左括号

				for (int i = 0; i < smallDocs.length; i++) {
					if (i != 0) {
						qs.appendOr();// 或者
					}
					qs.appendWhere(new SearchCondition(new KeywordExpression("A3.value2"), SearchCondition.LIKE,
							new KeywordExpression("'%" + smallDocs[i] + "%'")));
				}
				qs.appendCloseParen();// 右括号

			} else if ("IQCGroup".equals(curGroup)) {
				// 文档类型 受控PDF图纸
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A0.Ida2typedefinitionreference"),
						SearchCondition.EQUAL, new KeywordExpression("A2.ida2a2")));
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A2.name"), SearchCondition.EQUAL,
						new KeywordExpression("'" + ControlDocument + "'")));
			}
			System.out.println("---getDocByNumber sql:" + qs);

			QueryResult result = PersistenceHelper.manager.find(qs);
			if (result.hasMoreElements()) {
				Object[] obj = (Object[]) result.nextElement();
				doc = (WTDocument) obj[0];
				// doc = (WTDocument) result.nextElement();
				docList.add(doc);
			}

		} catch (WTException e) {
			e.printStackTrace();
		}
		return docList;

	}

	/**
	 * 获取文档主内容的cioids
	 * 
	 * @param doc
	 * @return
	 * @throws WTException
	 * @throws PropertyVetoException
	 */
	public static String getPrimaryId(WTDocument doc) throws WTException, PropertyVetoException {
		String cioids = "";
		if (doc != null) {
			ContentHolder contentholder = (ContentHolder) doc;
			contentholder = ContentHelper.service.getContents(contentholder);
			Vector v = ContentHelper.getContentListAll(contentholder);
			for (int j = 0; j < v.size(); j++) {
				ContentItem contentItem = (ContentItem) v.elementAt(j);
				if (contentItem.getRole().toString().equals("PRIMARY")) {
					ApplicationData appData = (ApplicationData) v.elementAt(j);

					ReferenceFactory ref = new wt.fc.ReferenceFactory();
					cioids = ref.getReferenceString(appData);
				}
			}
		}
		return cioids;
	}

	/**
	 * 获取所有视图部件add by lilin
	 * 
	 * @param wtObject
	 * @return
	 */
	public static WTArrayList getAllViewParts(WTObject wtObject) {
		WTArrayList objList = new WTArrayList();
		WTPart part = null;
		if (wtObject == null) {
			return objList;
		}
		if (wtObject instanceof WTPart) {
			part = (WTPart) wtObject;
		}
		try {

			View[] view = getAllViews();
			if (view != null && view.length > 0) {
				for (int i = 0; i < view.length; i++) {
					View partView = view[i];
					if (partView != null) {
						WTPart newPart = getWTPartByMasterAndView((WTPartMaster) part.getMaster(), partView);
						if (newPart != null) {
							if (!objList.contains(newPart)) {
								objList.add(newPart);
							}
						}
					}
				}
			}
		} catch (ViewException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		return objList;
	}

	/**
	 * 获取当前系统中所有的视图，返回值为一个数组。这个数组可能存在null
	 * 
	 * @return
	 * @throws ViewException
	 * @throws WTException
	 */
	public static View[] getAllViews() throws ViewException, WTException {

		return ViewHelper.service.getAllViews();
	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByMasterAndView(WTPartMaster master, View view) throws WTException {
		WTPart part = null;

		// 根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(view, null);
		try {
			standardConfig.setView(view);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		// 根据master和视图获取对应最新的视图版本零部件
		QueryResult qr1 = ConfigHelper.service.filteredIterationsOf(master, standardConfig);
		if (qr1.hasMoreElements()) {
			part = (WTPart) qr1.nextElement();
		}
		return part;
	}

	/**
	 * 判断当前系统用户是否在指定组下
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 *//*
		 * public static boolean roleContainUser() throws WTException { WTUser
		 * currentuser = (WTUser) SessionHelper.getPrincipal(); String curName =
		 * currentuser.getName();
		 * 
		 * // 读取组名 String configFilePath = "codebase" + File.separator + "ext" +
		 * File.separator + "tianma" + File.separator + "cfg" + File.separator +
		 * "TianmaPro.properties"; PropertiesUtil ut = new
		 * PropertiesUtil(configFilePath); String groupName =
		 * ut.getValueByKey("FAC.group"); WTGroup group = getGroup(groupName);
		 * List<WTUser> newUsers = getGroupMembersOfUser(group); for (WTUser u :
		 * newUsers) { if (curName.equals(u.getName())) { return true; } }
		 * 
		 * return false; }
		 */

	/**
	 * 获取组里面的成员
	 * 
	 * @param group
	 * @return
	 * @throws WTException
	 */
	public static List<WTUser> getGroupMembersOfUser(WTGroup group) throws WTException {
		List<WTUser> users = new ArrayList<WTUser>();
		Enumeration member = group.members();

		while (member.hasMoreElements()) {
			WTPrincipal principal = (WTPrincipal) member.nextElement();
			if (principal instanceof WTUser) {
				users.add((WTUser) principal);
			} else if (principal instanceof WTGroup) {
				List<WTUser> ausers = getGroupMembersOfUser((WTGroup) principal);
				for (int i = 0; i < ausers.size(); i++) {
					users.add(ausers.get(i));
				}
			}
		}
		return users;
	}

	/**
	 * 根据组名得到组
	 * 
	 * @param groupName
	 * @return
	 * @throws WTException
	 */
	public static WTGroup getGroup(String groupName) throws WTException {

		ExchangeContainer exchangecontainer = WTContainerHelper.service.getExchangeContainer();

		WTOrganization wtorganization = exchangecontainer.getOrganization();

		WTGroup group = null;
		group = OrganizationServicesHelper.manager.getGroup(groupName, wtorganization);// 组织下的组

		if (group == null) {

			group = OrganizationServicesHelper.manager.getGroup(groupName, exchangecontainer.getContextProvider());// 站点下的组

		}
		if (group == null) {
			throw new WTException("没有找到组: [" + groupName + "] ");
		}
		return group;
	}

	/*
	 * public static List<WTDocument> getDocByName(String name) throws WTException,
	 * RemoteException{ String curGroup = groupOfUser(); String ControlDocument =
	 * "cn.tianma.ControlDocument"; String ProcessDocuments =
	 * "cn.tianma.ProcessDocuments"; String SmallDocType = "SmallDocType";
	 * PropertiesUtil ut = new PropertiesUtil(configFilePath); String smallDocList =
	 * ut.getValueByKey("smallDocType.list"); String smallDocs[] =
	 * smallDocList.split(";"); List<WTDocument> docList = new
	 * ArrayList<WTDocument>(); WTDocument doc = null; String number = "";
	 * 
	 * List<WTDocument> list1 = getDocByName1(name); List<WTDocument> list = new
	 * ArrayList<WTDocument>(new HashSet(list1));// 去重 //WTDocumentMaster master =
	 * (WTDocumentMaster) doc.getMaster(); //getLatestRevision(master)
	 * 
	 * for(int j=0; j<list.size(); j++) { number = list.get(j).getNumber();
	 * 
	 * try {
	 * 
	 * QuerySpec qs = new QuerySpec(); int indexOfDocMater =
	 * qs.appendClassList(WTDocument.class, true); int indexOfDoc =
	 * qs.appendClassList(WTDocumentMaster.class, false); int indexOfType =
	 * qs.appendClassList(WTTypeDefinition.class, false);
	 * 
	 * qs.appendWhere(new SearchCondition(new
	 * KeywordExpression("A1.WTDocumentNumber"), SearchCondition.EQUAL, new
	 * KeywordExpression("'"+number+"'"))); qs.appendAnd(); qs.appendWhere(new
	 * SearchCondition(new KeywordExpression("A1.IdA2a2"), SearchCondition.EQUAL,
	 * new KeywordExpression("A0.Ida3masterreference")));
	 * 
	 * 
	 * if ("FACGroup".equals(curGroup)) { WTDocument d =
	 * DocUtil.getWTDocumentByNumber(number); WTPart p = getReferencePart(d); //文档类型
	 * 工艺文件，受控PDF qs.appendAnd(); qs.appendWhere(new SearchCondition(new
	 * KeywordExpression("A0.Ida2typedefinitionreference"), SearchCondition.EQUAL,
	 * new KeywordExpression("A2.ida2a2"))); qs.appendAnd(); qs.appendWhere(new
	 * SearchCondition(new KeywordExpression("A2.name"), SearchCondition.EQUAL, new
	 * KeywordExpression("'"+ProcessDocuments+"'")));
	 * 
	 * if(p != null) { if (TMTypeUtil.isFinishedGood(p) ||
	 * TMTypeUtil.isSemiFinishedGood(p)) { int valueIndex =
	 * qs.appendClassList(wt.iba.value.StringValue.class, false); int defIndex =
	 * qs.appendClassList(StringDefinition.class, false);
	 * 
	 * qs.appendAnd(); qs.appendWhere(new SearchCondition(new
	 * KeywordExpression("A0.ida2a2"), SearchCondition.EQUAL, new
	 * KeywordExpression("A3.ida3a4"))); qs.appendAnd(); qs.appendWhere(new
	 * SearchCondition(new KeywordExpression("A3.ida3a6"), SearchCondition.EQUAL,
	 * new KeywordExpression("A4.ida2a2")));
	 * 
	 * qs.appendAnd(); qs.appendWhere(new SearchCondition(new
	 * KeywordExpression("A4.name"), SearchCondition.EQUAL, new
	 * KeywordExpression("'"+SmallDocType+"'"))); qs.appendAnd();
	 * qs.appendOpenParen();// 左括号 for(int i=0; i<smallDocs.length; i++) { if(i!=0)
	 * { qs.appendOr();// 或者 } qs.appendWhere(new SearchCondition(new
	 * KeywordExpression("A2.value2"), SearchCondition.LIKE, new
	 * KeywordExpression("'%"+smallDocs[i]+"%'"))); } qs.appendCloseParen();// 右括号 }
	 * }
	 * 
	 * } else if("IQCGroup".equals(curGroup)) { //文档类型 受控PDF图纸 qs.appendAnd();
	 * qs.appendWhere(new SearchCondition(new
	 * KeywordExpression("A0.Ida2typedefinitionreference"), SearchCondition.EQUAL,
	 * new KeywordExpression("A2.ida2a2"))); qs.appendAnd(); qs.appendWhere(new
	 * SearchCondition(new KeywordExpression("A2.name"), SearchCondition.EQUAL, new
	 * KeywordExpression("'"+ControlDocument+"'"))); }
	 * 
	 * QueryResult result = PersistenceHelper.manager.find(qs); if
	 * (result.hasMoreElements()) { Object[] obj = (Object[]) result.nextElement();
	 * doc = (WTDocument) obj[0]; //doc = (WTDocument) result.nextElement();
	 * docList.add(doc); }
	 * 
	 * } catch (WTException e) { e.printStackTrace(); } }
	 * 
	 * 
	 * return docList;
	 * 
	 * }
	 */

	/**
	 * 根据文档名查找（模糊查询）
	 * 
	 * @param name
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static List<WTDocument> getDocByName(String name) throws WTException, RemoteException {
		List<WTDocument> docList = new ArrayList<WTDocument>();
		List<WTDocument> newAllDocList = new ArrayList<WTDocument>();
		List<WTDocument> lastDocList = new ArrayList<WTDocument>();
		QuerySpec qs = new QuerySpec();
		QueryResult qr = null;
		String curGroup = groupOfUser();
		System.out.println("---getDocByName  curGroup:" + curGroup);
		String SmallDocType = "SmallDocType";
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String smallDocList = ut.getValueByKey("smallDocType.list");
		String ControlDocument = ut.getValueByKey("IQC.queryType");
		String ProcessDocuments = ut.getValueByKey("FAC.queryType");
		String smallDocs[] = smallDocList.split(";");

		int indexOfDocMater = qs.appendClassList(WTDocumentMaster.class, true);
		int indexOfDoc = qs.appendClassList(WTDocument.class, false);
		int indexOfType = qs.appendClassList(WTTypeDefinition.class, false);

		SearchCondition sc = new SearchCondition(WTDocumentMaster.class, WTDocumentMaster.NAME, SearchCondition.LIKE,
				"%" + name.toUpperCase() + "%");
		qs.appendSearchCondition(sc);
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.IdA2a2"), SearchCondition.EQUAL,
				new KeywordExpression("A1.Ida3masterreference")));

		if ("FACGroup".equals(curGroup)) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.Ida2typedefinitionreference"),
					SearchCondition.EQUAL, new KeywordExpression("A2.ida2a2")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A2.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + ProcessDocuments + "'")));

			int valueIndex = qs.appendClassList(wt.iba.value.StringValue.class, false);
			int defIndex = qs.appendClassList(StringDefinition.class, false);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.ida2a2"), SearchCondition.EQUAL,
					new KeywordExpression("A3.ida3a4")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.ida3a6"), SearchCondition.EQUAL,
					new KeywordExpression("A4.ida2a2")));

			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A4.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + SmallDocType + "'")));
			qs.appendAnd();
			qs.appendOpenParen();// 左括号

			for (int i = 0; i < smallDocs.length; i++) {
				if (i != 0) {
					qs.appendOr();// 或者
				}
				qs.appendWhere(new SearchCondition(new KeywordExpression("A3.value2"), SearchCondition.LIKE,
						new KeywordExpression("'%" + smallDocs[i] + "%'")));
			}
			qs.appendCloseParen();// 右括号

		} else if ("IQCGroup".equals(curGroup)) {
			// 文档类型 受控PDF图纸
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A1.Ida2typedefinitionreference"),
					SearchCondition.EQUAL, new KeywordExpression("A2.ida2a2")));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A2.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + ControlDocument + "'")));

		}
		qs.appendOrderBy(new OrderBy(new KeywordExpression("A1.MODIFYSTAMPA2"), true));
		System.out.println("---getDocByName sql:" + qs);

		qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			Object[] obj = (Object[]) qr.nextElement();
			WTDocumentMaster master = (WTDocumentMaster) obj[0];
			WTDocument doc = (WTDocument) getLatestRevision(master);
			/*
			 * docList.add(doc); if ("IQCGroup".equals(curGroup)) { break; }
			 */
			// 增加状态校验
			if (State.RELEASED.equals(doc.getLifeCycleState())) {
				docList.add(doc);
				if ("IQCGroup".equals(curGroup)) {
					break;
				}
			}

		}

		newAllDocList = new ArrayList<WTDocument>(new HashSet(docList));// 去重
		//System.out.println("---getDocByName doclist.size:" + docList.size());
		//System.out.println("---getDocByName newAllDocList.size:" + newAllDocList.size());

		if ("FACGroup".equals(curGroup) && newAllDocList.size() != 0) {
			Map<String, WTDocument> map = getLatestDoc(newAllDocList);
			for (String key : map.keySet()) {
				WTDocument doc = map.get(key);
				lastDocList.add(doc);
			}
		} else {
			lastDocList = newAllDocList;
		}

		return lastDocList;
	}

	/**
	 * 根据输入的文档名筛选文档
	 * 
	 * @param docList
	 * @param name
	 * @return
	 */
	public static List<WTDocument> selectDocList(List<WTDocument> docList, String name) {
		List<WTDocument> list = new ArrayList<WTDocument>();
		if (docList.size() != 0) {
			for (int i = 0; i < docList.size(); i++) {
				WTDocument doc = docList.get(i);
				if (doc.getName().indexOf(name) != -1) {
					list.add(doc);
				}
			}
		}

		return list;
	}

	/**
	 * 查看当前用户是否有当前文档的读取权限以及文档是否有主内容
	 * 
	 * @param docNumber
	 * @return
	 * @throws JSONException
	 */
	public static String queryPermissions(String docNumber) throws JSONException {
		boolean hasModifiedPrivilege = false;
		JSONObject ob = new JSONObject();
		try {
			WTPrincipal wtUser = SessionHelper.getPrincipal();// 当前登录人
			// AccessPermission.DOWNLOAD 下载权限
			WTDocument WTDoc = BorrowWorkflowUtil.getDocByNumber(docNumber);// 当前文档
			hasModifiedPrivilege = AccessControlHelper.manager.hasAccess(wtUser, WTDoc, AccessPermission.READ);// 判断是否有权限下载
			FormatContentHolder aFormatContentHolder = (FormatContentHolder) ContentHelper.service.getContents(WTDoc);
			ApplicationData primary = (ApplicationData) ContentHelper.getPrimary(aFormatContentHolder);// 获取文档主内容
			if (primary != null) {
				if (hasModifiedPrivilege) {
					ob.put("status", "success");
					ob.put("message", "yes");
					ob.put("hint", "");
				} else {
					ob.put("status", "success");
					ob.put("message", "no");
					ob.put("hint", "您没有预览此图纸的权限");
				}
			} else {
				ob.put("status", "success");
				ob.put("message", "no");
				ob.put("hint", "此图纸没有主内容!");
			}
		} catch (WTException e) {
			ob.put("status", "error");
			ob.put("message", "接口错误！");
			e.printStackTrace();
		} catch (PropertyVetoException e) {
			ob.put("status", "error");
			ob.put("message", "接口错误！");
			e.printStackTrace();
		}
		return ob.toString();
	}

	/**
	 * 判断文档类型
	 * 
	 * @param doc
	 * @return
	 * @throws WTException
	 */
	public static String typeOfDoc(WTDocument doc) throws WTException {
		String str1 = "受控PDF图纸";
		String str2 = "工艺文件";
		String type = ClientTypedUtility.getTypeIdentifier(doc).getTypename();
		if (type.contains("cn.tianma.ControlDocument")) {
			return str1;
		} else if (type.contains("cn.tianma.ProcessDocuments")) {
			return str2;
		}

		return null;
	}

	/**
	 * 判断系统当前登录用户是否属于IQC组或工厂组
	 * 
	 * @return
	 * @throws WTException
	 */
	public static String groupOfUser() throws WTException {
		WTUser currentuser = (WTUser) SessionHelper.getPrincipal();
		String curName = currentuser.getName();

		// 读取组名
		String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma" + File.separator + "cfg"
				+ File.separator + "TianmaPro.properties";
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String FACGroup = ut.getValueByKey("FAC.group");
		String IQCGroup = ut.getValueByKey("IQC.group");
		WTGroup facgroup = getGroup(FACGroup);
		WTGroup iqcgroup = getGroup(IQCGroup);
		List<WTUser> facUsers = getGroupMembersOfUser(facgroup);
		List<WTUser> iqcUsers = getGroupMembersOfUser(iqcgroup);

		for (WTUser u : facUsers) {
			if (curName.equals(u.getName())) {
				return "FACGroup";
			}
		}
		for (WTUser u : iqcUsers) {
			if (curName.equals(u.getName())) {
				return "IQCGroup";
			}
		}

		return null;
	}

	/**
	 * 获取文档主内容的名称
	 * 
	 * @param document
	 * @return
	 * @throws WTException
	 * @throws PropertyVetoException
	 */
	public static String getDocPrimaryName(WTDocument document) throws WTException, PropertyVetoException {
		String name = "";
		ContentHolder contentHolder = ContentHelper.service.getContents((ContentHolder) document);
		ContentItem contentitem = ContentHelper.getPrimary((FormatContentHolder) contentHolder);
		if (contentitem != null) {
			ApplicationData applicationdata = (ApplicationData) contentitem;
			name = applicationdata.getFileName();

		}
		return name;

	}

	/**
	 * 根据对象属性名获取对应的属性值
	 * 
	 * @param obj
	 * @param ibaName
	 * @return
	 * @throws WTException
	 */
	public static String getIBAStringValue(WTObject obj, String ibaName) throws WTException {

		String value = null;
		String ibaClass = "wt.iba.definition.StringDefinition";

		try {
			if (obj instanceof IBAHolder) {
				IBAHolder ibaholder = (IBAHolder) obj;
				DefaultAttributeContainer defaultattributecontainer = getContainer(ibaholder);

				if (defaultattributecontainer != null) {

					AbstractValueView avv = getIBAValueView(defaultattributecontainer, ibaName, ibaClass);
					if (avv != null) {
						value = ((StringValueDefaultView) avv).getValue();
						wt.iba.value.litevalue.UnitValueDefaultView s;

					} else {
						value = "";
					}
				}
			}
		} catch (RemoteException e) {

			e.printStackTrace();
		}

		return value;
	}

	public static DefaultAttributeContainer getContainer(IBAHolder ibaholder) throws WTException, RemoteException {

		ibaholder = IBAValueHelper.service.refreshAttributeContainer(ibaholder, null, LOCALE, null);
		DefaultAttributeContainer defaultattributecontainer = (DefaultAttributeContainer) ibaholder
				.getAttributeContainer();

		return defaultattributecontainer;
	}

	public static AbstractValueView getIBAValueView(DefaultAttributeContainer dac, String ibaName, String ibaClass)
			throws WTException {

		AbstractValueView aabstractvalueview[] = null;
		AbstractValueView avv = null;

		aabstractvalueview = dac.getAttributeValues();
		for (int j = 0; j < aabstractvalueview.length; j++) {
			String thisIBAName = aabstractvalueview[j].getDefinition().getName();
			String thisIBAValue = IBAValueUtility.getLocalizedIBAValueDisplayString(aabstractvalueview[j], LOCALE);
			String thisIBAClass = (aabstractvalueview[j].getDefinition()).getAttributeDefinitionClassName();

			if (thisIBAName.equals(ibaName) && thisIBAClass.equals(ibaClass)) {
				avv = aabstractvalueview[j];

				break;
			}
		}

		return avv;
	}

}
